package com.cheyun.netsalev3.widget

import android.content.Context
import android.content.Intent
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import com.cheyun.netsalev3.R
import com.cheyun.netsalev3.adapter.ClueItemAdapter
import com.cheyun.netsalev3.bean.ClueItemData
import com.cheyun.netsalev3.bean.Row
import com.cheyun.netsalev3.databinding.ClueItemLayoutBinding
import com.cheyun.netsalev3.utils.CommonFunc
import com.cheyun.netsalev3.utils.SpaceItemDecoration
import com.cheyun.netsalev3.view.defeatdetails.DefeatDetailsActivity
import com.cheyunkeji.er.utils.ToastUtil

class ClueItemView: LinearLayout {
    var activity: AppCompatActivity? = null
    val datas = ArrayList<ClueItemData>()
    var clueData: Row? = null
    var mContext: Context? = null

    var binding: ClueItemLayoutBinding? = null
    private lateinit var adapter: ClueItemAdapter
    init {
        activity = context as AppCompatActivity
    }

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        this.mContext = context

        binding = ClueItemLayoutBinding.inflate(LayoutInflater.from(getContext()), this, true)
        initView()
    }
    private fun initView() {
        binding?.rlOper?.setLayoutManager(GridLayoutManager(this.context, 2))
        binding?.rlOper?.addItemDecoration(SpaceItemDecoration(this.context, 0, 8, 2))

        adapter = ClueItemAdapter(this.context)
        adapter.setItemClickListener { data, v ->
            clickOper(data.key, v)
        }
        binding?.rlOper?.adapter = adapter


    }
    fun setData(item:Row){
        datas.clear()
        clueData = item

        if (item.hashMap?.values == null) {
            return
        }

        for (i in item.hashMap.values) {
            if (i.id == -1) {
                datas.add(ClueItemData(i.name,i.key,i.value))
            }
            if (i.IsSelect && i.id != -1) {
                datas.add(ClueItemData(i.name,i.key,i.value))
            }
        }
        adapter.setData(datas)
    }

    fun clickOper(key: String, view: View) {
        if (key.equals("phone")) {
            if (clueData?.phone?.indexOf("*") == -1) {
                CommonFunc.copy(view.context, clueData?.phone)
                ToastUtil.showToast("复制成功")
            } else {
                ToastUtil.showToast("当前号码不能复制")
            }
        }else{
            var intent = Intent(view.context, DefeatDetailsActivity::class.java)
            intent.putExtra("tid", clueData?.tid)
            intent.putExtra("nkey", clueData?.neky)
            view.context.startActivity(intent)
        }
    }
}